package com.sq.util.web.initer;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.sq.util.BeanUtil;
import com.sq.util.ClassUtil;
import com.sq.util.StringUtil;
import com.sq.util.exception.CommonException;
import com.sq.util.exception.VisualException;
import com.sq.util.web.XssUtil;
import com.sq.util.web.validation.ParamName;
import com.sq.util.web.validation.ValidDate;
import com.sq.util.web.validation.ValidDateTime;
import com.sq.util.web.validation.ValidInt;
import com.sq.util.web.validation.ValidLong;
import com.sq.util.web.validation.ValidNotEmpty;
import com.sq.util.web.validation.ValidNotNull;
import com.sq.util.web.validation.ValidRegex;
import com.sq.util.web.validation.ValidStringLength;

/**
 * 
 * 通过注解，验证参数，并返回实体<br>
 * 使用方法 AA aa = InstanceIniter.initInstance(request, AA.class);
 */
public class FormIniter extends BaseIniter {

    private static Logger log = LoggerFactory.getLogger(FormIniter.class);

    /**
     * 根据实体类的配置，检查request的参数并返回对象实体<br>
     * model的字段可以用com.sq.util.annotation下面的注解验证。
     * 
     * @param request
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T initInstance(HttpServletRequest request, Class<T> cls) {
        Object obj = null;
        try {
            obj = cls.newInstance();
        } catch (Exception e) {
            throw new CommonException("不能实例化" + cls.getName());
        }
        List<Field> list = BeanUtil.getFields(cls);
        for (Field field : list) {
            if (field == null) {
                continue;
            }
            if (field.isAnnotationPresent(InitIgnore.class)) {
                continue;
            }
            String name = field.getName();
            if (field.isAnnotationPresent(ParamName.class)) {
                ParamName paramName = field.getAnnotation(ParamName.class);
                initProperty(cls, obj, field, request.getParameter(paramName.name()));
            } else {
                initProperty(cls, obj, field, request.getParameter(name));
            }
        }
        return (T) obj;
    }

    /**
     * 根据实体类的配置，检查request的参数并返回对象实体<br>
     * model的字段可以用com.sq.util.annotation下面的注解验证。
     * 
     * @param request
     * @param cls
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T initInstanceFromURI(HttpServletRequest request, Class<T> cls) {
        Object obj = null;
        try {
            obj = cls.newInstance();
        } catch (Exception e) {
            throw new CommonException("不能实例化" + cls.getName());
        }
        List<Field> list = BeanUtil.getFields(cls);
        String uri = request.getRequestURI();
        for (Field field : list) {
            if (field == null) {
                continue;
            }
            if (field.isAnnotationPresent(InitIgnore.class)) {
                continue;
            }
            if (field.isAnnotationPresent(ParamName.class)) {
                ParamName paramName = field.getAnnotation(ParamName.class);
                String value = getValueFromURI(uri, paramName.name());
                initProperty(cls, obj, field, value);
            } else {
                String name = field.getName();
                String value = getValueFromURI(uri, name);
                initProperty(cls, obj, field, value);
            }
        }
        return (T) obj;
    }

    /**
     * 批量提交时，检查request的参数并返回对象实体的list
     */
    @SuppressWarnings("unchecked")
    public static <T> List<T> initList(HttpServletRequest request, Class<T> cls) {
        Field[] arr = cls.getDeclaredFields();
        int length = -1;
        Map<Field, Object> map = new HashMap<Field, Object>();
        if (arr != null) {
            for (Field field : arr) {
                if (field == null) {
                    continue;
                }
                if (field.isAnnotationPresent(InitIgnore.class)) {
                    continue;
                }
                String name = field.getName();
                String[] valueArr = request.getParameterValues(name);
                if (valueArr == null) {
                    throw new VisualException(name + "提交的个数不对,为空");
                }
                if (length == -1) {
                    length = valueArr.length;
                } else if (length != valueArr.length) {
                    throw new VisualException(name + "提交的个数不对,为" + length);
                }
                map.put(field, valueArr);
            }
        }
        List<T> result = new LinkedList<T>();
        for (int i = 0; i < length; i++) {
            Object obj = null;
            try {
                obj = cls.newInstance();
            } catch (Exception e) {
                throw new CommonException("不能实例化" + cls.getName());
            }
            for (Map.Entry<Field, Object> entry : map.entrySet()) {
                Field field = entry.getKey();
                String[] valueStr = (String[]) entry.getValue();
                try {
                    initProperty(cls, obj, field, valueStr[i]);
                } catch (VisualException e) {
                    throw new VisualException("处理第" + (i + 1) + "行出错:" + e.getMessage());
                }
            }
            result.add((T) obj);
        }
        return result;
    }

    private static void initProperty(Class<?> cls, Object Obj, Field field, String valueStr) {
        try {
            _initProperty(cls, Obj, field, valueStr);
        } catch (VisualException e) {
            log.error("处理类[{}]的属性[{}]出错:{}", cls.getName(), field.getName(), e.getMessage());
            throw e;
        } catch (RuntimeException e) {
            log.error("处理类[" + cls.getName() + "]的属性[" + field.getName() + "]出错:", e);
            throw e;
        }
    }

    /**
     * 逐个参数检查和初始化
     */
    private static void _initProperty(Class<?> cls, Object Obj, Field field, String valueStr) {
        Object value = null;
        if (field.isAnnotationPresent(ValidNotNull.class)) {
            value = convert(field, valueStr);
            checkNotNull(field, value);
        } else if (field.isAnnotationPresent(ValidRegex.class)) {
            value = convert(field, valueStr);
            value = checkRegex(field, (String) value);
        } else if (field.isAnnotationPresent(ValidInt.class)) {
            value = convert(field, valueStr);
            value = checkInt(field, (Integer) value);
        } else if (field.isAnnotationPresent(ValidLong.class)) {
            value = convert(field, valueStr);
            value = checkLong(field, (Long) value);
        } else if (field.isAnnotationPresent(ValidNotEmpty.class)) {
            value = convert(field, valueStr);
            checkStringNotEmpty(field, (String) value);
        } else if (field.isAnnotationPresent(ValidStringLength.class)) {
            value = convert(field, valueStr);
            checkStringLength(field, (String) value);
        } else if (field.isAnnotationPresent(ValidDateTime.class)) {
            value = checkDateTime(field, valueStr);
        } else if (field.isAnnotationPresent(ValidDate.class)) {
            value = checkDate(field, valueStr);
        } else if (field.isAnnotationPresent(LimitLower.class)) {
            value = checkLimitLower(field, convert(field, valueStr));
        } else {
            if (valueStr == null) {
                return;
            }
            value = convert(field, valueStr);
        }
        if (value == null) {
            return;
        }
        if (ClassUtil.isString(field.getType())) {
            XssUtil.checkXSS(valueStr);
        }
        setProperty(cls, Obj, field, value);
    }

    private static String getValueFromURI(String uri, String name) {
        String findStr = "/" + name + "/";
        int index = uri.indexOf(findStr);
        if (index < 1) {
            return "";
        }
        char[] arr = uri.toCharArray();
        StringBuilder sb = new StringBuilder();
        for (int i = index + findStr.length(), length = arr.length; i < length; i++) {
            char c = arr[i];
            if (c == '/') {
                break;
            }
            sb.append(c);
        }
        return sb.toString();
    }

    private static Object checkDate(Field field, String valueStr) {
        ValidDate dateTime = field.getAnnotation(ValidDate.class);
        String name = dateTime.name();
        VisualException.isTrue(ClassUtil.isDate(field.getType()), "[{}]类型不是日期类型", name);
        boolean canBeNull = dateTime.canBeNull();
        if (StringUtil.isBlank(valueStr)) {
            if (canBeNull) {
                return null;
            } else {
                throw new VisualException("[{}]没传数据", name);
            }
        }
        return convertToDate(field, valueStr, dateTime.format());
    }

    private static Object checkDateTime(Field field, String valueStr) {
        ValidDateTime validDateTime = field.getAnnotation(ValidDateTime.class);
        String name = validDateTime.name();
        VisualException.isTrue(ClassUtil.isDate(field.getType()), "[{}]类型不是日期类型", name);
        boolean canBeNull = validDateTime.canBeNull();
        if (StringUtil.isBlank(valueStr)) {
            if (canBeNull) {
                return null;
            } else {
                throw new VisualException("[{}]没传数据", name);
            }
        }
        return convertToDate(field, valueStr, validDateTime.format());
    }

}
